<?php
// 这是系统自动生成的公共文件
use think\admin\service\AdminService;
use think\admin\service\NodeService;
use think\facade\Db;

function get_user_id()
{
    return session('user.id');
}

function firstImg($img_urls, $prefix = '|')
{
    $img_urls = explode($prefix, $img_urls);
    return empty($img_urls[0]) ? '' : $img_urls[0];
}

if (!function_exists('setLog')) {
    /**
     * JSON 数据读取与存储
     * @param array $data 数据名称
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function setLog($data)
    {
        return data_save('ContentLog', [
            'node' => NodeService::instance()->getCurrent(),
            'post_status' => $data['post_status'],
            'action' => $data['action'],
            'content' => $data['content'],
            'rel_type' => $data['rel_type'] ?: 1,
            'relate_id' => $data['relate_id'],
            'username' => AdminService::instance()->getUserName() ?: '-',
            'create_at' => date('Y-m-d H:i:s')
        ]);
    }
}

if (!function_exists('get_user_info')) {
    /**
     * 获取用户数据
     * @param int $type
     * @param array $where
     * @return array|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function get_user_info($where = [])
    {
        return Db::table('wechat_fans')->where($where)->findOrEmpty();
    }
}

if (!function_exists('getActInfo')) {
    /**
     * 获取
     * @param $act_id
     * @return array|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function getActInfo($act_id)
    {
        return Db::table('pt_group_act')->where(['id' => $act_id])->find() ?: [];

    }
}

/**
 * 时间
 * @param $dateTime
 * @param bool $date
 * @return false|string|string[]
 */
function friendlyDate($dateTime, $date = false)
{
    if ($date) {
        $dateTime = strtotime($dateTime);
        if (date('Y-m-d', $dateTime) == date('Y-m-d', strtotime('-1 day'))) {
            return "昨天";
        } elseif (date('Y-m-d', $dateTime) == date('Y-m-d', strtotime('-2 day'))) {
            return "前天";
        } elseif (date('Y', $dateTime) == date('Y')) {
            return date('m-d', $dateTime);
        }
        return date('Y-m-d', $dateTime);
    }
    $formats = [
        'year' => '%n% 年前',
        'month' => '%n% 月前',
        'day' => '%n% 天前',
        'hour' => '%n% 小时前',
        'minute' => '%n% 分钟前',
        'second' => '%n% 秒前',
    ];
    $timestamp = strtotime($dateTime);
    $now = time();
    $seconds = floor($now - $timestamp);
    $minutes = floor($seconds / 60);
    $hours = floor($minutes / 60);
    $days = floor($hours / 24);
    $months = floor($days / 30);
    $years = floor($months / 12);

    $diffType = '';
    $diffValue = 0;
    if ($years > 0) {
        $diffType = 'year';
        $diffValue = $years;
    } else {
        if ($months > 0) {
            $diffType = 'month';
            $diffValue = $months;
        } else {
            if ($days > 0) {
                $diffType = 'day';
                $diffValue = $days;
            } else {
                if ($hours > 0) {
                    $diffType = 'hour';
                    $diffValue = $hours;
                } else {
                    if ($minutes > 0) {
                        $diffType = 'minute';
                        $diffValue = $minutes;
                    } else {
                        $diffType = 'second';
                        $diffValue = $seconds == 0 ? ($seconds = 1) : $seconds;
                    }
                }
            }
        }
    }
    return str_replace('%n%', $diffValue, $formats[$diffType]);
}

/**
 * 字符串截取
 * @param $str
 * @param int $length
 * @param string $suffix
 * @return string
 */
function cut_str($str, $length = 15, $suffix = '...')
{
    return mb_strlen($str) > $length ? mb_substr($str, 0, $length, 'utf-8') . $suffix : $str;
}

function getOrderSn($prefix = 'top')
{
    $Ymd = date('YmdHis');
    $order_sn = $prefix . $Ymd . mt_rand(1000, 9999);
    $count = 0;
    if ($prefix == 'top') {
        $count = Db::table('pt_top_order')->where(['top_no' => $order_sn])->count();
    }
    if ($count > 0) $order_sn = getOrderSn($prefix);
    return $order_sn;
}

/**
 * 获取订单信息
 * @param $where
 * @return array|\think\Model
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\DbException
 * @throws \think\db\exception\ModelNotFoundException
 */
function getOrderInfo($where)
{
    return Db::table('pt_top_order')->alias('a')
        ->where($where)
        ->find() ?: [];
}

/**
 * 获取支付方式
 * @param $pay_type
 * @return string
 */
function getPayName($pay_type)
{
    $status_name = '-';
    switch ($pay_type) {
        case 0:
            $status_name = '待支付';
            break;
        case 1:
            $status_name = '微信支付';
            break;
    }
    return $status_name;
}

/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @param boolean $adv 是否进行高级模式获取（有可能被伪装）
 * @return mixed
 */
function get_client_ip($type = 0, $adv = false)
{
    $type = $type ? 1 : 0;
    static $ip = NULL;
    if ($ip !== NULL) return $ip[$type];
    if ($adv) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos = array_search('unknown', $arr);
            if (false !== $pos) unset($arr[$pos]);
            $ip = trim($arr[0]);
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u", ip2long($ip));
    $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}
